<template>
  <div class="container">
    <table class="up-insert">
      <tr>
        <td><input type="text" placeholder="请输入姓名" v-model="name"></td>
      <tr>
        <td><input type="text" placeholder="请输入工资" v-model="salary" @blur="checkSalary"></td>
      </tr>
      <tr>
        <td>
          <span>请选择性别</span>
          <label><input type="radio" name="sex" value="1" v-model="sex">男</label>
          <label><input type="radio" name="sex" value="0" v-model="sex">女</label>
        </td>
      </tr>
      <tr>
        <td>
          <el-button size="mini" type="primary" @click="inserData">添加</el-button>
          <el-button size="mini" type="info" @click="goBack">不想改了，返回</el-button>
          <el-button size="mini" type="warning" @click="upData">修改</el-button>
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
import {reqInsertUser,reqUpdata} from '../api/index'
  export default {
    data() {
      return {
        name:'',
        salary:'',
        sex:1
      }
    },
    methods: {
      // 验证工资格式
      checkSalary(){
        // 非零开头的最多带两位小数的数字
        let reg=/^([1-9][0-9]*)+(.[0-9]{1,2})?$/  
        if(reg.test(this.salary.trim())){
          return true
        }else{
          this.$message.error("工资必须是数字");
        }
      },
      async setData(reqInterface,userinfo){
        if(this.checkSalary()){
          const {code,msg} = await reqInterface(userinfo)
          if(code==200){
            this.$alert(msg, {
            confirmButtonText: "确定一下",
            callback: (confirm) => {
              this.$router.push("/");
            },
          });
          }
        }
      },
      inserData() {
        let userinfo={
          name:this.name.trim(),
          salary:this.salary.trim(),
          gander:this.sex
        }
        this.setData(reqInsertUser,userinfo)
      },
      goBack(){
        history.go(-1)
      },
      upData(){
        let id = this.$route.params.id
        let userinfo={
          id:id,
          name:this.name.trim(),
          salary:this.salary.trim(),
          gander:this.sex
        }
        this.setData(reqUpdata,userinfo)
      } 
    },
  }
</script>

<style lang="scss" scoped>
.container{
  width: 95%;
  text-align: center;
  .up-insert{
    width:30%;
    margin: 0 auto;
    text-align: center;
    border: 1px solid black;
    border-collapse: collapse;
    tr{
      width: 100%;
      height:60px;
      text-align: center;
      td{
        border: 1px solid black;
        >input{
          width: 60%;
          padding:10px;
        }        
        span{
          display: block;
        }
        label{
          text-align: center;
          >input{
            width:15%;
          }
        }
      }
    }
  }
}
</style>